package com.lagou.edu.servlet;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.annotation.Transactional;
import com.lagou.edu.utils.JsonUtils;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.StrUtils;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author 应癫
 */
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {
    private static Map<String,Object> map = new HashMap<>();  // 存储对象
    static {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = TransferServlet.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element =  beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                map.put(id,o);

            }

            TransactionManager transactionManager = (TransactionManager) map.get("transactionManager");//到容器直接拿了

            Reflections reflections = new Reflections("com.lagou.edu.service");
            Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Service.class);
            typesAnnotatedWith.forEach(p->{
                Service service = p.getAnnotation(Service.class);
                Class<?> interfaces = p.getInterfaces()[0];//如果有多个实现接口不知道会不会有问题
                String id = "";
                if (service.value()==null || service.value().equals("")){
                    String[] split = interfaces.getName().split("\\."); //拆分包名 com.lagou.edu.service.TransferService
                    id= StrUtils.toLowerCaseFirstOne(split[split.length-1]);//取 TransferService 进行首字母转小写变成 transferService
                }else {
                    id=service.value();//如果value有值就用value的值作为Bean的Id
                }
                try {
                    Class<?> clazz = Class.forName(p.getName());
                    Method[] methods = clazz.getMethods();
                    List<String> methodList=new ArrayList<>();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(Transactional.class)){
                            methodList.add(method.getName());
                        }
                    }
                    if (methodList!=null && methodList.size()>0){  //如果有Transactional注解则创建代理对象

                        Callback[] callbacks = new Callback[] {
                                new MethodInterceptor() {
                                    @Override
                                    public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                                        Object result = null;
                                        try{
                                            // 开启事务(关闭事务的自动提交)
                                            transactionManager.beginTransaction();

                                            result = methodProxy.invokeSuper(obj,objects);

                                            // 提交事务

                                            transactionManager.commit();
                                        }catch (Exception e) {
                                            e.printStackTrace();
                                            // 回滚事务
                                            transactionManager.rollback();

                                            // 抛出异常便于上层servlet捕获
                                            throw e;

                                        }
                                        return result;
                                    }
                                }, NoOp.INSTANCE
                        };

                        Enhancer enhancer = new Enhancer();
                        enhancer.setSuperclass(clazz);
                        enhancer.setCallbacks(callbacks);
                        enhancer.setCallbackFilter(new CallbackFilter() {
                            @Override
                            public int accept(Method method) {
                                if (methodList.contains(method.getName())){
                                    return 0;
                                }
                                return 1;
                            }
                        });
                        map.put(id,enhancer.create());
                    }else {
                        map.put(id,clazz.newInstance());
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            });



            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element =  propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if(method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject,map.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                map.put(parentId,parentObject);

            }
            Set<Field> fields = new Reflections(new FieldAnnotationsScanner())
                    .getFieldsAnnotatedWith(Autowired.class);//获取所有Autowired的属性

            map.forEach((key,value) -> {
                fields.forEach(field -> {
                    if (value.getClass().getName().contains(field.getDeclaringClass().getName())){  //两重循环用于判断map容器里哪个Bean存在Autowired的注解
                        //由于增强对象的类名有加上一个后缀所有只能用包含而不能用equals
                        try {
                            field.setAccessible(true);
                            field.set(value,map.get(field.getName())); //为Autowired注解的属性赋值
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                });
            });
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private TransferService transferService= (TransferService) map.get("transferService");//由于此类没有添加到容器里，不能通过 Autowired 赋值 先从map里面直接拿

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = moneyStr==null|| moneyStr.equals("")? 0 : Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            // 2. 调用service层方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
